package com.xiaobaibai.config;

import com.xiaobaibai.common.response.ResponseCode;
import com.xiaobaibai.common.response.ResponseFormat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@ControllerAdvice
public class GlobalException {

    /**
     * 传参错误
     */
    @ExceptionHandler( MissingServletRequestParameterException.class)
    @ResponseBody
    public ResponseFormat missingServletRequestParameterException(MissingServletRequestParameterException e){
        e.printStackTrace();
        return ResponseFormat.createFailureResponseOnlyMsg(ResponseCode.ERROR,e.getMessage());
    }

    /**
     * 断言错误
     */
    @ExceptionHandler( IllegalArgumentException.class)
    @ResponseBody
    public ResponseFormat illegalArgumentException(IllegalArgumentException e){
        e.printStackTrace();
        return ResponseFormat.createFailureResponseOnlyMsg(ResponseCode.ERROR,e.getMessage());
    }

    /**
     * 自定义异常
     */
    @ExceptionHandler( MyException.class)
    @ResponseBody
    public ResponseFormat myException(MyException e){
        e.printStackTrace();
        return ResponseFormat.createFailureResponseOnlyMsg(ResponseCode.ERROR,e.getMessage());
    }

    @ExceptionHandler( RuntimeException.class)
    @ResponseBody
    public ResponseFormat myException(RuntimeException e){
        e.printStackTrace();
        return ResponseFormat.createFailureResponseOnlyMsg(ResponseCode.ERROR,"服务器错误,请联系管理员");
    }

    /**
     * 全局捕获
     */
    @ExceptionHandler( Exception.class)
    @ResponseBody
    public ResponseFormat exception(Exception e){
        e.printStackTrace();
        return ResponseFormat.createFailureResponseOnlyMsg(ResponseCode.ERROR,"未知错误");
    }





}
